﻿using System;
using Com.Lancetinc.Evs.Data;
using Com.Lancetinc.Evs.Helpers;
using Com.Lancetinc.Evs.Services;
using Prism.Events;

namespace Com.Lancetinc.Evs.Events
{
    public class EventsListener
    {
        public static void Startup()
        {
            KnownAppEvents.RequireSaveCurrentExperEvent.Subscribe(OnRequireSaveCurrentExperEvent,
                ThreadOption.BackgroundThread);
            KnownAppEvents.VideoRecordStartedEvent.Subscribe(OnVideoRecordStartedEvent, ThreadOption.BackgroundThread);
            KnownAppEvents.VideoRecordPausedEvent.Subscribe(OnVideoRecordPausedEvent, ThreadOption.BackgroundThread);
            KnownAppEvents.VideoRecordStoppedEvent.Subscribe(OnVideoRecordStoppedEvent, ThreadOption.UIThread);
        }

        private static void OnRequireSaveCurrentExperEvent(RequireSaveCurrentExperEventArgs args)
        {
            // 保存实验数据
            AppRepositories.Exper.Save(args.ExperInfo.Exper.Exper);
        }

        /// <summary>
        /// 录像开始
        /// </summary>
        /// <param name="args"></param>
        private static void OnVideoRecordStartedEvent(VideoRecordStartedEventArgs args)
        {
            ActiveApp.Instance.InstManager.ChangeVideoRecording(true);
            KnownAppEvents.PublishRequireSaveCurrentExper(args.ExperInfo);
        }

        /// <summary>
        /// 录像暂停
        /// </summary>
        /// <param name="args"></param>
        private static void OnVideoRecordPausedEvent(VideoRecordPausedEventArgs args)
        {
            KnownAppEvents.PublishRequireSaveCurrentExper(args.ExperInfo);
        }

        /// <summary>
        /// 录像停止
        /// </summary>
        /// <param name="args"></param>
        private static void OnVideoRecordStoppedEvent(VideoRecordStoppedEventArgs args)
        {
            ActiveApp.Instance.InstManager.ChangeVideoRecording(false);

            var exper = args.ExperInfo;
            if (exper.Exper.EndTime == null)
            {
                exper.Exper.Exper.EndTime = DateTime.Now.FormatForDbUpdate();
                // 必须要直接保存，否则后续的ResetExper会先执行
                AppRepositories.Exper.Save(args.ExperInfo.Exper.Exper);
            }

            // 准备下一次实验
            ExperManager.Default.ResetExper(exper);
        }
    }
}